package cn.wolfcode.wolf2w.business.service.impl;

import cn.wolfcode.wolf2w.business.api.domain.Note;
import cn.wolfcode.wolf2w.business.api.domain.NoteContent;
import cn.wolfcode.wolf2w.business.mapper.NoteContentMapper;
import cn.wolfcode.wolf2w.business.mapper.NoteMapper;
import cn.wolfcode.wolf2w.business.query.NoteCondition;
import cn.wolfcode.wolf2w.business.query.NoteQuery;
import cn.wolfcode.wolf2w.business.service.INoteService;
import cn.wolfcode.wolf2w.common.core.constant.SecurityConstants;
import cn.wolfcode.wolf2w.common.core.context.SecurityContextHolder;
import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.common.core.utils.StringUtils;
import cn.wolfcode.wolf2w.destination.RemoteDestinationService;
import cn.wolfcode.wolf2w.destination.entity.TaDestination;
import cn.wolfcode.wolf2w.member.api.RemoteUserInfoService;
import cn.wolfcode.wolf2w.member.api.domain.UserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 旅游日记Service业务层处理
 *
 * @author libai
 * @date 2024-08-02
 */
@Service
@Transactional
public class NoteServiceImpl extends ServiceImpl<NoteMapper, Note> implements INoteService {
    @Autowired
    private RemoteDestinationService remoteDestinationService;

    @Autowired
    private NoteMapper noteMapper;

    @Autowired
    private RemoteUserInfoService remoteUserInfoService;

    @Autowired
    private NoteContentMapper noteContentMapper;

    @Override
    public IPage<Note> queryPage(NoteQuery qo) {
//        IPage<Note> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
//        QueryWrapper<Note> qw = new QueryWrapper<>();
//
//        qw.orderByDesc(qo.getOrderBy());
//
//        if(qo.getDayType() != -1){
//            NoteCondition dayCondition = NoteCondition.DAY_MAP.get(qo.getDayType());
//            qw.between("days", dayCondition.getMin(), dayCondition.getMax());
//        }
//
//        if(qo.getConsumeType() != -1){
//            NoteCondition consumeCondition = NoteCondition.CONSUME_MAP.get(qo.getConsumeType());
//            qw.between("avg_consume", consumeCondition.getMin(), consumeCondition.getMax());
//        }
//
//        if(qo.getTravelTimeType() != -1){
//            NoteCondition timeCondition = NoteCondition.TIME_MAP.get(qo.getTravelTimeType());
//            qw.between("month(travel_time)", timeCondition.getMin(), timeCondition.getMax());
//        }
//
//         IPage<Note> pageResult = noteMapper.selectPage(page, qw);
//        for (Note record : pageResult.getRecords()) {
//            R<UserInfo> one = remoteUserInfoService.getOne(record.getAuthorId(), SecurityConstants.INNER);
//            record.setAuthor(one.getData());
//
//        }
//        return pageResult;

        IPage<Note> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        LambdaQueryChainWrapper<Note> wrapper = lambdaQuery()
                .like(StringUtils.hasText(qo.getTitle()), Note::getTitle, qo.getTitle())
                .eq(qo.getIsPublic() != null, Note::getIsPublic, qo.getIsPublic())
                .eq(qo.getStatus() != null, Note::getStatus, qo.getStatus())
                .eq(qo.getDestId() != null, Note::getDestId, qo.getDestId());

        //旅行天数
        NoteCondition day = NoteCondition.DAY_MAP.get(qo.getDayType());
        if (day != null) {
            wrapper.between(Note::getDays, day.getMin(), day.getMax());
        }

        //人均消费
        NoteCondition avg = NoteCondition.CONSUME_MAP.get(qo.getConsumeType());
        if (avg != null) {
            wrapper.between(Note::getAvgConsume, avg.getMin(), avg.getMax());
            //wrapper.ge("day", day.getMin()).le("day", day.getMax());
        }

        //旅行时间
        NoteCondition time = NoteCondition.TIME_MAP.get(qo.getTravelTimeType());
        if (time != null) {
            wrapper.apply("month(travel_time) BETWEEN {0} AND {1}", time.getMin(), time.getMax());
        }

        //前端用户
        for (Note record : page.getRecords()) {
            R<UserInfo> ret = remoteUserInfoService.getOne(record.getAuthorId(), SecurityConstants.INNER);
            if (R.isSuccess(ret)) {
                record.setAuthor(ret.getData());
            }
        }
        wrapper.orderByDesc(StringUtils.hasText(qo.getOrderBy()), "viewnum".equals(qo.getOrderBy()) ? Note::getViewnum : Note::getCreateTime);
        wrapper.page(page);

        for (Note record : page.getRecords()) {
            record.setAuthor(remoteUserInfoService.getOne(record.getAuthorId(), SecurityConstants.INNER).getData());
        }


        return page;
    }

    @Override
    public Note queryById(Long id) {
        Note note = noteMapper.selectById(id);
        R<UserInfo> r = remoteUserInfoService.getOne(note.getAuthorId(), SecurityConstants.INNER);
        UserInfo userInfo = r.getData();
        note.setAuthor(userInfo);
        NoteContent content = noteContentMapper.selectById(id);
        note.setContent(content);
        return note;
    }

    @Override
    public List<Note> queryViewnnumTop3ByDestId(Long destId) {
        List<Note> list = lambdaQuery().eq(Note::getDestId, destId)
                .orderByDesc(Note::getViewnum)
                .last("limit 3")
                .list();
        return list;
    }

    @Override
    public void insert(Note note) {
        R<TaDestination> r = remoteDestinationService.getById(note.getDestId());
        note.setDestName(r.getData().getName());
        note.setAuthorId(SecurityContextHolder.getUserId());
        Date date = new Date();
        note.setCreateTime(date);
        note.setUpdateTime(date);
        note.setStatus("0");
        note.setViewnum(0l);
        note.setReplynum(0l);
        note.setFavornum(0l);
        note.setSharenum(0l);
        note.setThumbsupnum(0l);
        save(note);
        NoteContent noteContent = new NoteContent();
        noteContent.setId(note.getId());
        noteContent.setContent(note.getContent().getContent());
        noteContentMapper.insert(noteContent);
    }
}
